<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="horizontal" >
          <a-row :gutter="8">
            <a-col :md="8" :sm="24">
              <a-form-item label="操作用户" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select showSearch v-model="queryParam.userId" placeholder="请选择" allowClear :filterOption="filterOption">
                  <a-select-option v-for="item in dictUser" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="请求标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="queryParam.title" placeholder="支持模糊查询"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="成功标志" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.code" placeholder="请选择" allowClear >
                    <a-select-option value="-1">失败</a-select-option>
                    <a-select-option value="0">成功</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="请求年月" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number v-model="queryParam.ym" placeholder="年月格式如：201901" style="width: 100%"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="请求时间开始" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    :disabledDate="disabledStartDate"
                    showTime
                    style="width: 100%"
                    format="YYYY-MM-DD HH:mm:ss"
                    v-model="queryParam.begTimeStart"
                    placeholder="请输入开始时间"
                    @openChange="handleStartOpenChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="请求时间结束" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    :disabledDate="disabledEndDate"
                    showTime
                    style="width: 100%"
                    format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请输入结束时间"
                    v-model="queryParam.begTimeEnd"
                    :open="endOpen"
                    @openChange="handleEndOpenChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="请求参数" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.reqParams" placeholder="支持模糊查询"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="所属路由" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    showSearch
                    v-model="queryParam.routerId"
                    style="width: 100%"
                    :value="routerSelectTreeValue"
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="单选"
                    treeNodeFilterProp="title"
                    allowClear
                    treeDefaultExpandAll
                    :treeData="routerSelectTreeData"
                    @change="onChangeRouterSelectTree"
                    @search="onSearchRouterSelectTree"
                    @select="onSelectRouterSelectTree"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="所属功能" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    showSearch
                    v-model="queryParam.funcId"
                    style="width: 100%"
                    :value="funcSelectTreeValue"
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="单选"
                    treeNodeFilterProp="title"
                    allowClear
                    treeDefaultExpandAll
                    :treeData="funcSelectTreeData"
                    @change="onChangeFuncSelectTree"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="请求API" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.reqApi" placeholder="精确查找"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-checkbox @change="onHistroyChange">查询历史</a-checkbox>
                <a-button type="primary" @click="() =>{this.findListBtn()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {this.clearAll()}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <vxe-grid
        class="vxe-table-antd"
        resizable
        show-overflow
        ref="listTable"
        stripe
        border
        highlight-hover-row
        highlight-current-row
        highlight-hover-column
        highlight-current-column
        highlight-cell
        height="400"
        size="small"
        :columns="tableColumn"
        row-id="reqLogId"
        :data="tableData"
        :loading="loading"
        :start-index="(tablePage.currentPage - 1) * tablePage.pageSize"
        :pager-config="tablePage"
        @page-change="handlePageChange"
      >
      </vxe-grid>
      <a-modal
        title="请求参数详情"
        centered
        style="top: 10px;"
        width="80%"
        destroyOnClose
        v-model="visible"
        :footer="null"
      >
        <json-viewer :value="reqParams"></json-viewer>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { getRouterTreeList, getRouterFunctionList,getUserDict,getFunctionTreeList,getOplogApiList } from "@/services/system/api"
import modal from 'ant-design-vue/es/modal'
// import modal from 'ant-design-vue/es/modal'
import moment from 'moment'
const flagMap = {
  '-1': {
    status: 'error',
    text: '失败'
  },
  '0': {
    status: 'success',
    text: '成功'
  }
}
export default {
  name: 'UserReqLog',
  components: {
  },
  data () {
    return {
      description: '用户请求日志',
      dictData: {},
      dictUser: [],
      endOpen: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      form: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      loading: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 20
      },
      tableColumn: [
        { type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号' },
        { field: 'reqLogId', title: '请求日志Id', visible: false, fixed: 'left', align: 'center', width: 150 },
        { field: 'title', title: '请求标题', align: 'center', fixed: 'left', width: 200 },
        { field: 'reqApi', title: '请求API', align: 'center', width: 250 },
        { field: 'userId', title: '用户Id', visible: false, align: 'center', width: 150 },
        { field: 'userName', title: '用户名', align: 'center', width: 150 },
        { field: 'fullName', title: '姓名', align: 'center', width: 200 },
        { field: 'ym', title: '所属年月', align: 'center', width: 80 },
        { field: 'code', title: '成功标识', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatflag(row.code)] } } },
        { field: 'message', title: '描述', align: 'center', width: 300 },
        { field: 'begTime', title: '请求时间', align: 'center', width: 200 },
        { field: 'endTime', title: '返回时间', align: 'center', width: 200 },
        { field: 'countTime', title: '耗时（秒）', align: 'center', width: 80 },
        { field: 'routerId', title: '路由id', align: 'center', width: 150 },
        { field: 'funcId', title: '功能Id', align: 'center', width: 150 },
        { field: 'ip', title: '请求客户端IP', align: 'center', width: 150 },
        { field: 'serverIp', title: '服务器IP', align: 'center', width: 250 },
        { field: 'serverPort', title: '服务器端口', align: 'center', width: 200 },
        { field: 'servletContext', title: '服务名', align: 'center', width: 200 },
        { field: 'reqParams', title: '请求参数', align: 'center', width: 350 },
        { field: 'action', title: '详情', align: 'center', fixed: 'right', width: 100, slots: { default: ({ row }) => { return [ <a-button type="link" onClick={ () => this.openParamInfo(row.reqParams) } >参数详情</a-button> ] } } }
      ],
      tableData: [],
      selectData: {},
      routerSelectTreeValue: undefined,
      funcSelectTreeValue: undefined,
      routerSelectTreeData: [],
      funcSelectTreeData: [],
      isHistoryChecked: false,
      reqParams: null
    }
  },
  created () {
    // 数据初始化
    // 数据字典初始化
    const params = {}
    params.permissionFlag = false
    this.$http.post(getUserDict,params).then(res => {
      this.dictUser = res.result
    })
    const queryParams = {}
    setTimeout(() => {
      this.$http.post(getRouterTreeList,queryParams).then((res) => {
        this.routerSelectTreeData = res.result.routerList
      }).catch(() => {
      })
    }, 20)
    this.getFunctionTreeList()
  },
  methods: {
    moment,
    onChangeRouterSelectTree (value) {
      console.log(value)
      this.routerSelectTreeValue = value
      this.getFunctionTreeList()
    },
    onSearchRouterSelectTree () {
      console.log(...arguments)
    },
    onSelectRouterSelectTree () {
      console.log(...arguments)
    },
    onChangeFuncSelectTree (value) {
      console.log(value)
      this.funcSelectTreeValue = value
    },
    getFunctionTreeList () {
      const params = {}
      if (this.routerSelectTreeValue) {
        params.id = this.routerSelectTreeValue
        setTimeout(() => {
          this.$http.post(getRouterFunctionList,params).then((res) => {
            this.funcSelectTreeData = res.result.functionList
          }).catch(() => {
          })
        }, 20)
      } else {
        this.$http.post(getFunctionTreeList,params).then((res) => {
          this.funcSelectTreeData = res.result.functionList
        }).catch(() => {
        })
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    formatflag (cellValue) {
      let value = cellValue
      if (value) {
        if (value !== '0') {
          value = '-1'
        }
        const text = flagMap[value].text
        const status = flagMap[value].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    disabledStartDate (loginTimeBeg) {
      const loginTimeEnd = this.queryParam.loginTimeEnd
      if (!loginTimeBeg || !loginTimeEnd) {
        return false
      }
      return loginTimeBeg.valueOf() > loginTimeEnd.valueOf()
    },
    disabledEndDate (loginTimeEnd) {
      const loginTimeBeg = this.queryParam.loginTimeBeg
      if (!loginTimeEnd || !loginTimeBeg) {
        return false
      }
      return loginTimeBeg.valueOf() >= loginTimeEnd.valueOf()
    },
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange (open) {
      this.endOpen = open
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handlePageChange ({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageNum = currentPage
      this.tablePage.pageSize = pageSize
      this.findList()
    },
    findListBtn () {
      this.tablePage.currentPage = 1
      this.tablePage.pageNum = 1
      this.findList()
    },
    // 列表查询
    findList () {
      this.loading = true
      const params = Object.assign(this.queryParam, this.tablePage)
      params.history = this.isHistoryChecked
      setTimeout(() => {
         this.$http.post(getOplogApiList,params).then((res) => {
          const data = res.result.list
          this.tableData = data
          this.tablePage.total = res.result.total
          this.tablePage.currentPage = res.result.pageNum
          this.tablePage.pageNum = res.result.pageNum
          this.tablePage.pageSize = res.result.pageSize
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }, 20)
    },
    clearAll () {
      this.queryParam = {}
      this.findList()
    },
    openParamInfo (value) {
      if (value) {
        this.reqParams = JSON.parse(value)// JSON.stringify(value, null, 4)
        this.visible = true
      } else {
        modal.info({ title: '提示', content: '参数为空' })
      }
    },
    onHistroyChange (e) {
      this.isHistoryChecked = e.target.checked
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
